package com.fanxuankai.boot.apollo.openapi.component;

import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenReleaseDTO;
import com.fanxuankai.boot.apollo.openapi.autoconfigure.ApolloConfigPublishProperties;
import com.fanxuankai.boot.apollo.openapi.autoconfigure.ApolloOpenApiProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author fanxuankai
 */
public class ApolloConfigPublisher implements ApplicationRunner {
    private final ApolloOpenApiClient client;
    private final ApolloOpenApiProperties properties;
    private final ApolloConfigPublishProperties publishProperties;
    private static final Logger LOGGER = LoggerFactory.getLogger(ApolloConfigPublisher.class);

    public ApolloConfigPublisher(ApolloOpenApiClient client, ApolloOpenApiProperties apolloOpenApiProperties,
                                 ApolloConfigPublishProperties apolloOpenApiConfigPublishProperties) {
        this.client = client;
        this.properties = apolloOpenApiProperties;
        this.publishProperties = apolloOpenApiConfigPublishProperties;
    }

    @Override
    public void run(ApplicationArguments args) {
        OpenReleaseDTO latestActiveRelease = client.getLatestActiveRelease(properties.getAppId(), properties.getEnv(),
                properties.getClusterName(), properties.getNamespace());
        if (latestActiveRelease != null
                && Objects.equals(latestActiveRelease.getName(), publishProperties.getReleaseTitle())) {
            LOGGER.info("Ignore publishing. To publish, please modify the release title: {}", properties.getNamespace());
            return;
        }
        NamespaceReleaseDTO dto = new NamespaceReleaseDTO();
        String releaseTitle = publishProperties.getReleaseTitle();
        if (StringUtils.isEmpty(releaseTitle)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String datetimeStr = sdf.format(new Date());
            releaseTitle = datetimeStr + "-release";
        }
        dto.setReleaseTitle(releaseTitle);
        dto.setReleaseComment(publishProperties.getReleaseComment());
        dto.setReleasedBy(publishProperties.getReleasedBy());
        dto.setEmergencyPublish(publishProperties.isEmergencyPublish());
        OpenReleaseDTO releaseDTO = client.publishNamespace(properties.getAppId(), properties.getEnv(),
                properties.getClusterName(), properties.getNamespace(), dto);
        LOGGER.info("Published successfully, result: {}", releaseDTO);
    }
}
